//
//  BLApiSystem.m
//  BasketBallLeagues
//
//  Created by kenshin on 5/6/17.
//  Copyright © 2017 kenshin. All rights reserved.
//

#import "BLApiSystem.h"

#define kLocalRegionJson @"LocalRegionData.json"
#define LocalQuarterJson @"LocalQuarterData.json"
#define LocalYearJson @"LocalYearData.json"
#define LocalRuleJson @"LocalRuleData.json"

#define kRequestMaxRetryTime 300

@interface BLApiSystem ()


@property (nonatomic) NSInteger requestRetryTime; //初始资源总体的请求重试次数，包括region，year，rule等公用同一个

@property (nonatomic) BOOL regionRequestSuccess;
@property (nonatomic) BOOL quarterRequestSuccess;
@property (nonatomic) BOOL yearRequestSuccess;
@property (nonatomic) BOOL ruleRequestSuccess;

@end

@implementation BLApiSystem

+ (instancetype)sharedInstance
{
    static BLApiSystem *singleOjbect = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        singleOjbect = [[self alloc] init];
    });
    return singleOjbect;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _requestRetryTime = 0;
    }
    return self;
}

- (void)prepareDefData {
    [self requestRegion];
    [self requestQuarter];
    [self requestYear];
    [self requestCompetitionRules];
}

- (void)requestRegion {
    [BLApi POST:URL_System_Region parameters:nil decodeClass:nil completion:^(id responseObject, id jsonObject, NSError *error) {
        if (error) {
            DDLogWarn(@"请求地区信息失败:%@", error);
            self.requestRetryTime++;
            if (self.requestRetryTime < kRequestMaxRetryTime) {
                DDLogWarn(@"即将重试");
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self requestRegion];
                });
            } else {
                DDLogWarn(@"达到重试上限，不再重试");
            }
        } else {
            BOOL success = [(NSDictionary *)responseObject writeToFile:[CacheDirectory stringByAppendingString:kLocalRegionJson] atomically:YES];
            
            DDLogDebug(@"地区:%@-%@", @(success), responseObject);
        }
    }];
}

+ (NSArray *)loadLocalRegion {
    NSDictionary *region = [NSDictionary dictionaryWithContentsOfFile:[CacheDirectory stringByAppendingString:kLocalRegionJson]];
    return region[@"regions"];
}

/*
- (void)requestQuarter {
    [BLApi POST:URL_System_Quarter parameters:nil decodeClass:[BLQuarterResponse class] completion:^(id responseObject, id jsonObject, NSError *error) {
        if (error) {
            DDLogWarn(@"请求赛季信息失败:%@", error);
            self.requestRetryTime++;
            if (self.requestRetryTime < kRequestMaxRetryTime) {
                DDLogWarn(@"即将重试");
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self requestQuarter];
                });
            } else {
                DDLogWarn(@"达到重试上限，不再重试");
            }
        } else {
            BOOL success = [NSKeyedArchiver archiveRootObject:responseObject toFile:[CacheDirectory stringByAppendingString:LocalQuarterJson]];
            DDLogDebug(@"赛季:%@-%@", @(success), responseObject);
        }
        
    }];
}
*/

/*
+ (BLQuarterResponse *)loadLocalQuarters {
    return [NSKeyedUnarchiver unarchiveObjectWithFile:[CacheDirectory stringByAppendingString:LocalQuarterJson]];
}
 */
/*
- (void)requestCompetitionRules {
    [BLApi POST:URL_System_competition_rules parameters:nil decodeClass:[BLCompetitionRuleResponse class] completion:^(id responseObject, id jsonObject, NSError *error) {
        if (error) {
            DDLogWarn(@"请求赛制失败:%@", error);
            self.requestRetryTime++;
            if (self.requestRetryTime < kRequestMaxRetryTime) {
                DDLogWarn(@"即将重试");
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self requestCompetitionRules];
                });
            } else {
                DDLogWarn(@"达到重试上限，不再重试");
            }
        } else {
            BOOL success = [NSKeyedArchiver archiveRootObject:responseObject toFile:[CacheDirectory stringByAppendingString:LocalRuleJson]];
            DDLogDebug(@"赛制:%@-%@", @(success), responseObject);
        }
    }];
}
 */

/*
+ (BLCompetitionRuleResponse *)loadLocalCompetitionRules {
    return [NSKeyedUnarchiver unarchiveObjectWithFile:[CacheDirectory stringByAppendingString:LocalRuleJson]];
}
*/

- (void)requestYear {
    [BLApi POST:URL_System_Year parameters:nil decodeClass:nil completion:^(id responseObject, id jsonObject, NSError *error) {
        if (error) {
            DDLogWarn(@"请求年份信息失败:%@", error);
            self.requestRetryTime++;
            if (self.requestRetryTime < kRequestMaxRetryTime) {
                DDLogWarn(@"即将重试");
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self requestYear];
                });
            } else {
                DDLogWarn(@"达到重试上限，不再重试");
            }
        } else {
            BOOL success = [(NSDictionary *)responseObject writeToFile:[CacheDirectory stringByAppendingString:LocalYearJson] atomically:YES];
            
            DDLogDebug(@"年份:%@-%@", @(success), responseObject);
        }
        
    }];
}

+ (NSArray<NSString *> *)loadLocalYear {
    NSDictionary *region = [NSDictionary dictionaryWithContentsOfFile:[CacheDirectory stringByAppendingString:LocalYearJson]];
    return region[@"years"];
}

@end
